package com.hyx.java.interceptor;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hyx.java.base.BaseResult;
import com.hyx.java.constant.HyxConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 允许客户端携带跨域cookie，当Access-Control-Allow-Credentials设为true的时候，Access-Control-Allow-Origin不能设为星号
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许指定域访问跨域资源
        httpServletResponse.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        // 允许浏览器发送的请求消息头
        httpServletResponse.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        // 允许浏览器在预检请求成功之后发送的实际请求方法名
        httpServletResponse.setHeader("Access-Control-Allow-Methods", request.getHeader("Access-Control-Request-Method"));
        String token = request.getHeader(HyxConstant.LOGIN_TOKEN_KEY);
        if (StringUtils.isEmpty(token)) {
            sendJsonMessage(httpServletResponse, BaseResult.fail("401", "未登录！"));
            return false;
        }
        String cache = redisTemplate.opsForValue().get(token);
        if (StringUtils.isEmpty(cache)) {
            sendJsonMessage(httpServletResponse, BaseResult.fail("403", "token已过期！"));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private void sendJsonMessage(HttpServletResponse response, BaseResult result) throws Exception {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSONUtil.toJsonStr((result)));
        writer.close();
        response.flushBuffer();
    }
}
